package util

import (
	"bufio"
	"os"
	"path/filepath"
	"strings"
)

// GetFiles 递归目录下所有文件
func GetFiles(fileName string) ([]string, error) {
	var files []string

	err := filepath.Walk(fileName, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if !info.IsDir() {
			files = append(files, path)
		}

		return nil
	})
	return files, err
}

// WriteFile 写入文件内容
func WriteFile(lines []string, fileName string) {
	file, err := os.Open(fileName)
	if err != nil {
		return
	}
	defer file.Close()

	for _, line := range lines {
		_, err := file.WriteString(line)
		if err != nil {
			return
		}
	}
}

// FileRead 读取文件内容
func FileRead(fileName string) ([]string, error) {
	file, err := os.Open(fileName)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	var lines []string
	scanner := bufio.NewScanner(file)

	for scanner.Scan() {
		line := scanner.Text()
		// 去除前后空格
		line = strings.TrimSpace(line)

		lines = append(lines, line)
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return lines, nil
}
